<template>
  <view class="page page-container">
    <!-- 顶部筛选区 -->
    <view class="filter-section">
      <view class="department-filter">
        <text class="filter-title">科室选择</text>
        <scroll-view 
          scroll-x 
          class="scroll-department" 
          show-scrollbar="false"
        >
          <view class="department-list">
            <view
              v-for="(item, index) in departments"
              :key="index"
              :class="['department-item', currentDepartment === item ? 'active' : '']"
              @tap="selectDepartment(item)"
            >
              {{ item }}
            </view>
          </view>
        </scroll-view>
      </view>

      <!-- 日期筛选 -->
      <view class="date-filter">
        <text class="filter-title">日期选择</text>
        <view class="date-picker-wrapper">
          <uni-datetime-picker
            type="date"
            v-model="selectedDate"
            @change="handleDateChange"
            :border="false"
            placeholder="选择日期"
            class="date-picker">
          </uni-datetime-picker>
        </view>
      </view>
    </view>

    <!-- 就诊记录列表 -->
    <scroll-view 
      scroll-y 
      class="record-list"
      refresher-enabled
      :refresher-triggered="isRefreshing"
      @refresherrefresh="onRefresh"
      @scrolltolower="onLoadMore"
    >
      <!-- 空数据提示 -->
      <view v-if="!isLoading && medicalRecords.length === 0" class="empty-tip">
        <text class="empty-text">暂无问诊记录</text>
      </view>

      <view
        v-else
        v-for="(record, index) in medicalRecords"
        :key="index"
        class="record-card"
      >
        <view class="patient-info">
          <view class="avatar-box">
            <image 
              :src="record.avatar_url" 
              class="avatar" 
              mode="aspectFill"
            />
          </view>
          <view class="info-content">
            <view class="name-gender">
              <text class="name">{{ record.name }}</text>
              <text class="gender-age">{{ record.gender }} {{ record.age }}岁</text>
            </view>
            <view class="visit-info">
              <text class="time">就诊时间：{{ record.visit_time }}</text>
              <text class="department">科室：{{ record.department }}</text>
            </view>
          </view>
        </view>

        <view class="diagnosis-info" @tap="toggleExpand(index)">
          <view class="allergy-info">
            <text class="label">过敏史：</text>
            <text class="value">{{ record.allergy || '无' }}</text>
          </view>
          <view class="doctor">
            <text class="label">主治医生：</text>
            <text class="value">{{ record.doctor }}</text>
          </view>
          <view class="diagnosis">
            <text class="label">诊断结果：</text>
            <text class="value">{{ record.diagnosis }}</text>
          </view>
        </view>

        <view v-if="record.is_expanded" class="detail-info">
          <view class="detail-item">
            <text class="detail-label">主诉：</text>
            <text class="detail-value">{{ record.main_complaint }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">现病史：</text>
            <text class="detail-value">{{ record.present_illness }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">既往史：</text>
            <text class="detail-value">{{ record.past_history }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">检查结果：</text>
            <text class="detail-value">{{ record.check_result }}</text>
          </view>
        </view>

        <view class="action-buttons">
          <button class="action-btn" @tap="exportRecord(record)">
            <uni-icons 
              type="download" 
              size="16" 
              color="#2979ff"
            />
            导出
          </button>
          <button class="action-btn share-btn" @tap="showShareOptions(record)">
            <uni-icons 
              type="redo-filled" 
              size="16" 
              color="#2979ff"
            />
            分享
          </button>
        </view>
      </view>
      
      <!-- 加载提示 -->
      <view class="loading-more" v-if="isLoading">
        <text class="loading-text">加载中...</text>
      </view>
      <view class="loading-more" v-else-if="!isLoading && medicalRecords.length > 0">
        <text class="loading-text">没有更多数据了</text>
      </view>
    </scroll-view>

    <!-- 分享选项弹窗 -->
    <uni-popup ref="sharePopup" type="bottom">
      <view class="share-options">
        <view class="share-title">分享方式</view>
        <view class="share-content">
          <view class="share-grid">
            <button class="share-button" @tap="shareToWechat('friend')">
              <image src="../../static/images/wechat-friend.png" mode="aspectFit"></image>
              <text>微信好友</text>
            </button>
            <button class="share-button" @tap="generateQRCode">
              <image src="../../static/images/qrcode.png" mode="aspectFit"></image>
              <text>二维码</text>
            </button>
            <button class="share-button" @tap="copyLink">
              <image src="../../static/images/copy-link.png" mode="aspectFit"></image>
              <text>复制链接</text>
            </button>
          </view>
        </view>
        <button class="cancel-btn" @tap="closeSharePopup">取消</button>
      </view>
    </uni-popup>

    <!-- 二维码预览弹窗 -->
    <uni-popup ref="qrcodePopup" type="center">
      <view class="qrcode-preview">
        <view class="qrcode-title">分享二维码</view>
        <view class="qrcode-content">
          <image :src="qrcodeUrl" mode="aspectFit" class="qrcode-image"></image>
          <text class="qrcode-tip">扫描二维码查看就诊记录</text>
        </view>
        <view class="qrcode-actions">
          <button class="qrcode-btn save-btn" @tap="saveQRCodeToAlbum">保存到相册</button>
          <button class="qrcode-btn cancel-btn" @tap="closeQRCodePopup">取消</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'
import { apiBaseUrl, minioBaseUrl, getMinioUrl } from '../../config/api'

// 声明uni-app和微信小程序的全局变量
declare const uni: any;
declare const wx: {
  env: {
    USER_DATA_PATH: string;
  };
  getFileSystemManager: () => {
    writeFileSync: (filePath: string, data: any, encoding: string) => void;
    accessSync: (filePath: string) => void;
    unlinkSync: (filePath: string) => void;
    saveFile: (options: {
      tempFilePath: string;
      filePath: string;
      success?: (res: any) => void;
      fail?: (error: any) => void;
    }) => void;
  };
};

// 添加 getCurrentPages 的类型声明
declare function getCurrentPages(): any[];

interface MedicalRecord {
  gender: string;
  visit_time: string;
  present_illness: string;
  past_history: string;
  allergy: string;
  diagnosis: string;
  doctor: string;
  main_complaint: string;
  is_expanded: boolean;
  check_result: string;
  avatar_url: string;
  patient_id: number;
  name: string;
  department: string;
  age: number;
}

// 状态定义
const departments = ref(['全部', '内科', '外科', '儿科', '妇科', '骨科', '眼科', '口腔科'])
const currentDepartment = ref('全部')
const selectedDate = ref('')

// 分页和刷新状态
const isRefreshing = ref(false)
const isLoading = ref(false)
const hasMore = ref(true)
const page = ref(1)

// 数据定义
const allMedicalRecords = ref<MedicalRecord[]>([]) // 保存所有原始数据
const medicalRecords = computed(() => {
  let filteredRecords = [...allMedicalRecords.value]
  
  // 科室筛选
  if (currentDepartment.value !== '全部') {
    filteredRecords = filteredRecords.filter(record => 
      record.department === currentDepartment.value
    )
  }
  
  // 日期筛选
  if (selectedDate.value) {
    const selectedDateOnly = typeof selectedDate.value === 'string' 
      ? selectedDate.value.split('T')[0].split(' ')[0]
      : '';
      
    console.log('当前选择的日期:', selectedDateOnly);
    
    filteredRecords = filteredRecords.filter(record => {
      const recordDate = record.visit_time.split(' ')[0];
      const isMatch = recordDate === selectedDateOnly;
      
      console.log('记录日期比较:', {
        当前记录: record.visit_time,
        记录日期: recordDate,
        选择日期: selectedDateOnly,
        是否匹配: isMatch
      });
      
      return isMatch;
    });
    
    // 如果筛选后没有数据，显示提示
    if (filteredRecords.length === 0) {
      uni.showToast({
        title: `${selectedDateOnly} 没有就诊记录`,
        icon: 'none',
        duration: 2000
      });
    }
  }
  
  return filteredRecords;
})

// 添加visitId参数到状态定义部分
const visitId = ref<string | null>(null);

// 获取就诊记录(微信开发者工具上调试)
const getMedicalRecords = async () => {
  try {
    // 如果有通过二维码扫描传入的visitId参数，优先获取该记录的详情
    if (visitId.value) {
      await loadSingleVisitRecord();
      return;
    }

    isLoading.value = true;
    uni.showLoading({
      title: '加载中...'
    });
    
    const [err, res] = await uni.request({
      url: `${apiBaseUrl}/patient/visits/selectAll`,
      method: 'GET'
    }).then(res => [null, res]).catch(err => [err, null]);

    if (err) {
      throw new Error('网络请求失败');
    }

    const { code, result } = res.data as { code: number; result: MedicalRecord[] };
    if (code === 200 && result) {
      // 格式化日期显示
      allMedicalRecords.value = result.map(item => {
        const date = new Date(item.visit_time);
        const formattedDate = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
        
        return {
          ...item,
          is_expanded: false,
          visit_time: formattedDate
        };
      });
      hasMore.value = false;
    } else {
      uni.showToast({
        title: '获取就诊记录失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('请求错误:', error);
    uni.showToast({
      title: '网络错误',
      icon: 'none'
    });
  } finally {
    isLoading.value = false;
    uni.hideLoading();
    isRefreshing.value = false;
  }
};

// 添加加载单个就诊记录的方法
const loadSingleVisitRecord = async () => {
  try {
    isLoading.value = true;
    uni.showLoading({
      title: '加载中...'
    });
    
    const [err, res] = await uni.request({
      url: `${apiBaseUrl}/patient/visits/${visitId.value}`,
      method: 'GET'
    }).then(res => [null, res]).catch(err => [err, null]);

    if (err) {
      throw new Error('获取就诊记录失败');
    }

    const { code, result } = res.data as { code: number; result: MedicalRecord };
    if (code === 200 && result) {
      // 格式化日期显示
      const date = new Date(result.visit_time);
      const formattedDate = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
      
      const formattedRecord = {
        ...result,
        is_expanded: true, // 自动展开详情
        visit_time: formattedDate
      };
      
      allMedicalRecords.value = [formattedRecord];
      
      // 设置当前记录，用于分享等功能
      currentRecord.value = formattedRecord;
      
      // 根据扫码记录的科室自动选择对应科室
      if (formattedRecord.department && departments.value.includes(formattedRecord.department)) {
        currentDepartment.value = formattedRecord.department;
      }
    } else {
      uni.showToast({
        title: '获取就诊记录失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('请求错误:', error);
    uni.showToast({
      title: '网络错误',
      icon: 'none'
    });
  } finally {
    isLoading.value = false;
    uni.hideLoading();
  }
};

// 页面加载时的处理函数
onMounted(() => {
  // 从页面参数中获取visitId（扫码传入的参数）
  const query = uni.getLaunchOptionsSync()?.query || {};
  // 使用全局的 getCurrentPages 函数
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  
  // 使用类型断言解决options属性不存在的问题
  const options = (currentPage as any)?.options || query;
  
  console.log('页面参数:', options);
  
  // 处理小程序码的scene参数
  if (options.scene) {
    try {
      // 解析场景值
      const scene = decodeURIComponent(options.scene);
      
      // 手动解析参数
      const sceneParams: Record<string, string> = {};
      const paramPairs = scene.split('&');
      for (let i = 0; i < paramPairs.length; i++) {
        const pair = paramPairs[i].split('=');
        if (pair.length === 2) {
          sceneParams[pair[0]] = pair[1];
        }
      }
      
      visitId.value = sceneParams['visitId'] || null;
      console.log('从场景值获取visitId:', visitId.value);
    } catch (error) {
      console.error('解析场景值失败:', error);
    }
  } 
  // 处理直接传入的id参数
  else if (options.id) {
    visitId.value = options.id;
    console.log('从options直接获取id:', visitId.value);
  }
  
  // 获取就诊记录
  getMedicalRecords();
});

// 方法定义
const selectDepartment = (department: string) => {
  currentDepartment.value = department;
  // 不需要重新请求数据，computed属性会自动处理筛选
}

const handleDateChange = (value: string) => {
  if (!value) {
    selectedDate.value = '';
    return;
  }
  
  // 格式化日期
  const date = new Date(value);
  const formattedDate = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
  
  console.log('选择的日期:', {
    原始值: value,
    格式化后: formattedDate
  });
  
  selectedDate.value = formattedDate;
};

const toggleExpand = (index: number) => {
  const record = medicalRecords.value[index];
  const originalIndex = allMedicalRecords.value.findIndex(
    item => item.patient_id === record.patient_id
  );
  if (originalIndex !== -1) {
    allMedicalRecords.value[originalIndex].is_expanded = !allMedicalRecords.value[originalIndex].is_expanded;
  }
}

// 导出就诊记录
const exportRecord = async (record: MedicalRecord) => {
  let loadingShown = false;
  try {
    // 显示加载提示
    uni.showLoading({
      title: '导出中...'
    });
    loadingShown = true;
    
    // 构建请求URL
    const requestUrl = `${apiBaseUrl}/patient/visits/export?patientId=${record.patient_id}&exportType=pdf`;
    console.log('导出请求URL:', requestUrl);
    
    // 先检查API是否可访问
    try {
      const [checkErr, checkRes] = await uni.request({
        url: requestUrl,
        method: 'HEAD',
        timeout: 5000
      }).then(res => [null, res]).catch(err => [err, null]);
      
      if (checkErr) {
        console.error('API检查失败:', checkErr);
        throw new Error('API服务不可用');
      }
      
      console.log('API检查结果:', checkRes);
      
      // 检查服务器返回的状态码
      if (checkRes.statusCode === 500) {
        // 尝试使用 GET 请求获取更详细的错误信息
        const [detailErr, detailRes] = await uni.request({
          url: requestUrl,
          method: 'GET',
          timeout: 5000
        }).then(res => [null, res]).catch(err => [err, null]);
        
        console.log('详细错误信息:', detailRes);
        
        // 显示更友好的错误提示
        if (loadingShown) {
          uni.hideLoading();
          loadingShown = false;
        }
        
        uni.showModal({
          title: '导出失败',
          content: '服务器配置问题导致PDF生成失败，请联系客服或稍后再试。',
          showCancel: false
        });
        
        return;
      }
    } catch (checkError) {
      console.error('API检查异常:', checkError);
      throw new Error('无法连接到导出服务');
    }
    
    // 真机环境使用downloadFile方式
    uni.downloadFile({
      url: requestUrl,
      success: (downloadRes) => {
        console.log('下载响应:', downloadRes);
        
        if (downloadRes.statusCode === 200) {
          // 直接打开文件预览
          uni.openDocument({
            filePath: downloadRes.tempFilePath,
            showMenu: true,
            success: () => {
              console.log('打开文档成功');
              if (loadingShown) {
                uni.hideLoading();
                loadingShown = false;
              }
              uni.showToast({
                title: '导出成功',
                icon: 'success'
              });
            },
            fail: (err) => {
              console.error('打开文档失败', err);
              if (loadingShown) {
                uni.hideLoading();
                loadingShown = false;
              }
              uni.showToast({
                title: '文件打开失败',
                icon: 'none'
              });
            }
          });
        } else if (downloadRes.statusCode === 500) {
          console.error('下载失败，服务器错误:', downloadRes);
          if (loadingShown) {
            uni.hideLoading();
            loadingShown = false;
          }
          
          uni.showModal({
            title: '导出失败',
            content: '服务器配置问题导致PDF生成失败，请联系客服或稍后再试。',
            showCancel: false
          });
        } else {
          console.error('下载失败，状态码:', downloadRes.statusCode);
          if (loadingShown) {
            uni.hideLoading();
            loadingShown = false;
          }
          uni.showToast({
            title: `下载失败 (${downloadRes.statusCode})`,
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('下载失败', err);
        if (loadingShown) {
          uni.hideLoading();
          loadingShown = false;
        }
        uni.showToast({
          title: `下载失败: ${err.errMsg || '未知错误'}`,
          icon: 'none'
        });
      }
    });
  } catch (error) {
    console.error('导出错误:', error);
    if (loadingShown) {
      uni.hideLoading();
      loadingShown = false;
    }
    uni.showToast({
      title: `导出失败: ${error.message || '未知错误'}`,
      icon: 'none'
    });
  } finally {
    // 确保在任何情况下都关闭 loading
    if (loadingShown) {
      uni.hideLoading();
      loadingShown = false;
    }
  }
}

// 分享相关的状态
const sharePopup = ref();
const currentRecord = ref<any>(null);
const shareImage = ref('');
const qrcodePopup = ref();
const qrcodeUrl = ref('');

// 分享数据
const shareData = ref({
  title: '就诊记录',
  path: '/pages/consultation/consultation',
  imageUrl: ''
});

// 显示分享选项
const showShareOptions = async (record: any) => {
  if (!record) {
    uni.showToast({
      title: '分享数据无效',
      icon: 'none'
    });
    return;
  }
  currentRecord.value = record;
  sharePopup.value.open();
};

// 关闭分享弹窗
const closeSharePopup = () => {
  sharePopup.value.close();
};

// 生成分享图片
const generateShareImage = async (record: any) => {
  try {
    const [err, res] = await uni.request({
      url: `${apiBaseUrl}/patient/visits/share-image?visitId=${record.patient_id}`,
      method: 'POST',
    }).then(res => [null, res]).catch(err => [err, null]);

    if (err) {
      console.error('生成分享图片请求失败:', err);
      throw new Error('生成分享图片失败');
    }

    const { code, result, msg } = res.data;
    if (code !== 200 || !result) {
      console.error('生成分享图片响应异常:', msg);
      throw new Error(msg || '生成分享图片失败');
    }

    console.log('服务器返回的分享图片路径:', result);
    
    // 确保result是字符串
    const imagePath = result as string;
    
    // 使用新的工具函数处理URL
    const imageUrl = getMinioUrl(imagePath);
    
    // 预加载图片，确认是否可访问
    return new Promise<string>((resolve, reject) => {
      uni.getImageInfo({
        src: imageUrl,
        success: () => {
          console.log('图片可访问:', imageUrl);
          resolve(imagePath); // 返回原始结果，让后续处理添加minioBaseUrl
        },
        fail: (err) => {
          console.error('图片不可访问:', imageUrl, err);
          // 图片无法访问时，使用默认图片
          reject(new Error('分享图片无法访问'));
        }
      });
    });
  } catch (error) {
    console.error('生成分享图片异常:', error);
    throw error;
  }
};

// 分享到微信
const shareToWechat = async (scene: 'friend') => {
  if (!currentRecord.value) {
    uni.showToast({
      title: '分享数据无效',
      icon: 'none'
    });
    return;
  }

  try {
    // 先生成分享图片
    const shareImageUrl = await generateShareImage(currentRecord.value);
    shareImage.value = shareImageUrl;
    
    // 使用工具函数获取完整URL
    const fullImageUrl = getMinioUrl(shareImageUrl);
    
    // 设置分享参数
    const baseShareParams = {
      title: `${currentRecord.value.name || '患者'}的就诊记录`,
      path: `/pages/consultation/consultation?id=${currentRecord.value.patient_id || ''}`,
      imageUrl: fullImageUrl // 使用完整的图片URL
    };

    shareData.value = baseShareParams;

    console.log('分享数据:', shareData.value);

    // 提示用户通过胶囊按钮分享可以看到生成的分享图
    uni.showToast({
      title: '点击右上角"···"分享可查看完整分享图',
      icon: 'none',
      duration: 1500
    });
    
    closeSharePopup();
  } catch (error) {
    console.error('准备分享数据失败:', error);
    uni.showToast({
      title: '分享准备失败',
      icon: 'none'
    });
  }
};

// 添加小程序分享回调函数
const onShareAppMessage = (res: any) => {
  if (!currentRecord.value) {
    return {
      title: '就诊记录',
      path: '/pages/consultation/consultation'
    };
  }
  
  // 使用工具函数获取完整URL
  const fullImageUrl = shareImage.value ? getMinioUrl(shareImage.value) : '';
  
  return {
    title: `${currentRecord.value.name || '患者'}的就诊记录`,
    imageUrl: fullImageUrl || '../../static/logo.png', // 优先使用动态生成的图片，失败时使用静态图片
    path: `/pages/consultation/consultation?id=${currentRecord.value.patient_id || ''}`
  };
};

// 页面分享处理函数
defineExpose({
  onShareAppMessage
});

// 添加页面分享配置
const pageMetaData = {
  navigationBarTitleText: '就诊记录',
  enableShareAppMessage: true,  // 启用分享给朋友
  enableShareTimeline: true     // 启用分享到朋友圈
}

// 设置页面标题和分享功能
uni.setNavigationBarTitle({
  title: pageMetaData.navigationBarTitleText
});

// 生成二维码
const generateQRCode = async () => {
  try {
    if (!currentRecord.value) {
      uni.showToast({
        title: '分享数据无效',
        icon: 'none'
      });
      return;
    }

    uni.showLoading({
      title: '生成二维码中...'
    });

    const [err, res] = await uni.request({
      url: `${apiBaseUrl}/patient/visits/qrcode`,
      method: 'POST',
      data: {
        page: 'pages/consultation/consultation',
        scene: currentRecord.value.patient_id.toString(),
        width: 280
      }
    }).then(res => [null, res]).catch(err => [err, null]);

    if (err || !res.data.result) {
      throw new Error('生成二维码失败');
    }
    
    // 处理base64数据
    const base64Data = res.data.result as string;
    // 将base64数据转换为临时文件路径
    const tempFilePath = await new Promise<string>((resolve, reject) => {
      const fs = uni.getFileSystemManager();
      const filePath = `${wx.env.USER_DATA_PATH}/qrcode_${Date.now()}.png`;
      
      // 移除base64头部
      const base64 = base64Data.replace(/^data:image\/\w+;base64,/, '');
      
      fs.writeFile({
        filePath,
        data: base64,
        encoding: 'base64',
        success: () => resolve(filePath),
        fail: (err) => reject(err)
      });
    });
    
    // 使用临时文件路径
    qrcodeUrl.value = tempFilePath;
    
    // 预检查二维码图片是否可访问
    await new Promise<void>((resolve, reject) => {
      uni.getImageInfo({
        src: tempFilePath,
        success: () => {
          console.log('二维码图片可访问');
          resolve();
        },
        fail: (err) => {
          console.error('二维码图片不可访问:', err);
          reject(new Error('二维码图片无法访问'));
        }
      });
    });
    
    // 图片检查通过后执行
    closeSharePopup();
    qrcodePopup.value.open();
  } catch (error) {
    console.error('生成二维码失败:', error);
    uni.showToast({
      title: '生成二维码失败',
      icon: 'none'
    });
  } finally {
    uni.hideLoading();
  }
};

// 更新保存二维码到相册的方法，添加权限处理
const saveQRCodeToAlbum = async () => {
  try {
    // 检查保存到相册的权限
    const checkPermission = async () => {
      // 获取用户授权状态
      const authResult = await new Promise<any>((resolve, reject) => {
        uni.getSetting({
          success: (res) => resolve(res),
          fail: (err) => reject(err)
        });
      });
      
      // 如果没有相册权限
      if (!authResult.authSetting['scope.writePhotosAlbum']) {
        try {
          // 从未授权过，直接申请授权
          await new Promise<void>((resolve, reject) => {
            uni.authorize({
              scope: 'scope.writePhotosAlbum',
              success: () => resolve(),
              fail: (err) => reject(err)
            });
          });
        } catch (error) {
          // 如果授权失败，可能是用户拒绝了，引导用户打开设置页面
          const modalResult = await new Promise<any>((resolve, reject) => {
            uni.showModal({
              title: '提示',
              content: '需要您授权保存图片到相册的权限，是否去设置打开?',
              confirmText: '去设置',
              cancelText: '取消',
              success: (res) => resolve(res),
              fail: (err) => reject(err)
            });
          });
          
          if (!modalResult.confirm) {
            throw new Error('用户拒绝授权');
          }
          
          // 打开设置页面
          await new Promise<void>((resolve) => {
            uni.openSetting({
              success: () => resolve()
            });
          });
          
          // 再次获取授权状态
          const settingResult = await new Promise<any>((resolve, reject) => {
            uni.getSetting({
              success: (res) => resolve(res),
              fail: (err) => reject(err)
            });
          });
          
          if (!settingResult.authSetting['scope.writePhotosAlbum']) {
            throw new Error('未获得相册权限');
          }
        }
      }
    };
    
    // 显示加载提示
    uni.showLoading({
      title: '保存中...'
    });
    
    // 先检查/获取权限
    await checkPermission();
    
    // 检查二维码URL是否有效
    if (!qrcodeUrl.value) {
      throw new Error('二维码图片无效');
    }
    
    // 预先检查图片是否可访问
    await new Promise<void>((resolve, reject) => {
      uni.getImageInfo({
        src: qrcodeUrl.value,
        success: () => resolve(),
        fail: (err) => {
          console.error('二维码图片不可访问:', qrcodeUrl.value, err);
          reject(new Error('二维码图片无法访问'));
        }
      });
    });
    
    // 判断 qrcodeUrl 是否为本地文件路径
    const isLocalFile = qrcodeUrl.value.startsWith('wxfile://') || qrcodeUrl.value.startsWith('file://');
    
    let filePath = qrcodeUrl.value;
    
    // 如果不是本地文件，则需要下载
    if (!isLocalFile) {
      const downloadResult = await new Promise<any>((resolve, reject) => {
        uni.downloadFile({
          url: qrcodeUrl.value,
          success: (res) => resolve(res),
          fail: (err) => reject(err)
        });
      });

      if (downloadResult.statusCode !== 200) {
        throw new Error('下载二维码失败');
      }
      
      filePath = downloadResult.tempFilePath;
    }

    // 保存图片到相册
    await new Promise<void>((resolve, reject) => {
      uni.saveImageToPhotosAlbum({
        filePath: filePath,
        success: () => resolve(),
        fail: (err) => reject(new Error('保存到相册失败'))
      });
    });

    uni.showToast({
      title: '已保存到相册',
      icon: 'success'
    });
    closeQRCodePopup();
  } catch (error) {
    console.error('保存二维码失败:', error);
    uni.showToast({
      title: error.message || '保存失败',
      icon: 'none'
    });
  } finally {
    uni.hideLoading();
  }
};

// 关闭二维码预览弹窗
const closeQRCodePopup = () => {
  qrcodePopup.value.close();
};

// 复制链接
const copyLink = () => {
  if (!currentRecord.value) {
    uni.showToast({
      title: '分享数据无效',
      icon: 'none'
    });
    return;
  }

  // 使用小程序path
  const link = `pages/consultation/consultation?id=${currentRecord.value.patient_id}`;
  uni.setClipboardData({
    data: link,
    success: () => {
      uni.showToast({
        title: '小程序路径已复制',
        icon: 'success'
      });
      closeSharePopup();
    }
  });
};

// 下拉刷新
const onRefresh = async () => {
  isRefreshing.value = true;
  page.value = 1;
  await getMedicalRecords();
}

// 加载更多
const onLoadMore = async () => {
  if (!hasMore.value) return;
  page.value += 1;
  await getMedicalRecords();
}
</script>

<style>
/* 页面基础样式 */
page {
  height: 100vh;
  background-color: #f5f5f5;
}

.page-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  margin: 0;
  padding: 0;
}

/* 筛选区域样式 */
.filter-section {
  background-color: #ffffff;
  padding: 0;
  margin: 0;
  width: 100%;
  flex-shrink: 0;
}

/* 科室筛选 */
.department-filter {
  padding: 10rpx 0 5rpx;
  margin: 0;
}

.filter-title {
  font-size: 14px;
  color: #666666;
  padding: 0 20rpx;
  margin: 0 0 8rpx;
  display: block;
}

.scroll-department {
  white-space: nowrap;
}

.department-list {
  display: inline-flex;
  padding: 0 20rpx;
}

.department-item {
  padding: 16rpx 32rpx;
  margin-right: 20rpx;
  background-color: #f8f8f8;
  border-radius: 32rpx;
  font-size: 14px;
  color: #333333;
}

.department-item.active {
  background-color: #2979ff;
  color: #ffffff;
}

/* 日期筛选 */
.date-filter {
  margin-bottom: 15rpx;  /* 减少日期筛选区域的下方间距 */
}

.date-picker-wrapper {
  padding: 0 20rpx;
  margin-top: 5rpx;  /* 微调日期选择器的上方间距 */
}

.date-picker {
  width: 100%;
  background-color: #f8f8f8;
  border-radius: 8rpx;
}

/* 记录列表样式 */
.record-list {
  flex: 1;
  overflow: auto;
  padding: 20rpx;
}

.record-card {
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
}

/* 患者信息 */
.patient-info {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
}

.avatar-box {
  width: 100rpx;
  height: 100rpx;
  margin-right: 20rpx;
  border-radius: 50rpx;
  overflow: hidden;
}

.avatar {
  width: 100%;
  height: 100%;
}

.info-content {
  flex: 1;
}

.name-gender {
  margin-bottom: 10rpx;
}

.name {
  font-size: 16px;
  color: #333333;
  font-weight: 500;
  margin-right: 20rpx;
}

.gender-age {
  font-size: 14px;
  color: #666666;
}

.visit-info {
  font-size: 14px;
  color: #666666;
}

.time {
  margin-right: 20rpx;
}

/* 诊断信息 */
.diagnosis-info {
  padding: 20rpx 0;
  border-top: 1px solid #f0f0f0;
  border-bottom: 1px solid #f0f0f0;
}

.doctor, 
.diagnosis {
  margin-bottom: 10rpx;
}

.label {
  font-size: 14px;
  color: #666666;
}

.value {
  font-size: 14px;
  color: #333333;
}

/* 详细信息 */
.detail-info {
  padding: 20rpx 0;
}

.detail-item {
  margin-bottom: 16rpx;
}

.detail-label {
  font-size: 14px;
  color: #666666;
}

.detail-value {
  font-size: 14px;
  color: #333333;
  line-height: 1.5;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  justify-content: flex-end;
  margin-top: 20rpx;
  gap: 20rpx;
}

.action-btn {
  margin: 0;
  padding: 0 32rpx;
  height: 64rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  color: #2979ff;
  background-color: #ecf5ff;
  border: none;
  border-radius: 32rpx;
}

.action-btn:active {
  background-color: #d4e8ff;
}

.action-btn .uni-icons {
  margin-right: 8rpx;
}

/* 加载更多样式 */
.loading-more {
  padding: 20rpx 0;
  text-align: center;
}

.loading-text {
  font-size: 24rpx;
  color: #999999;
}

/* 空数据提示样式 */
.empty-tip {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40rpx;
  color: #999;
}

.empty-text {
  font-size: 28rpx;
}

.share-options {
  background-color: #f6f6f6;
  border-radius: 20rpx 20rpx 0 0;
  padding: 30rpx 0;
}

.share-title {
  text-align: center;
  font-size: 28rpx;
  color: #888;
  margin-bottom: 20rpx;
}

.share-content {
  background-color: #fff;
  padding: 30rpx 20rpx;
}

.share-grid {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20rpx;
}

.share-button {
  background: none;
  border: none;
  padding: 0;
  margin: 0;
  width: 140rpx;
  height: 140rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.share-button::after {
  border: none;
}

.share-button image {
  width: 80rpx;
  height: 80rpx;
  margin-bottom: 8rpx;
}

.share-button text {
  font-size: 24rpx;
  color: #333;
}

.cancel-btn {
  margin: 20rpx 30rpx 0;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  background-color: #fff;
  color: #333;
  border-radius: 12rpx;
  font-size: 32rpx;
  border: none;
}

.qrcode-preview {
  background-color: #fff;
  border-radius: 20rpx;
  width: 600rpx;
  padding: 40rpx;
}

.qrcode-title {
  text-align: center;
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 30rpx;
}

.qrcode-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20rpx 0;
}

.qrcode-image {
  width: 400rpx;
  height: 400rpx;
  margin-bottom: 20rpx;
}

.qrcode-tip {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 30rpx;
}

.qrcode-actions {
  display: flex;
  gap: 20rpx;
}

.qrcode-btn {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  border-radius: 40rpx;
  font-size: 28rpx;
  border: none;
}

.qrcode-btn.save-btn {
  background-color: #2979ff;
  color: #fff;
}

.qrcode-btn.save-btn:active {
  background-color: #2567e3;
}

.qrcode-btn.cancel-btn {
  background-color: #f5f5f5;
  color: #333;
}

.qrcode-btn.cancel-btn:active {
  background-color: #e8e8e8;
}
</style>
  